package com.eascs.brand.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.brand.dao.O2oBrandDao;
import com.eascs.brand.entity.O2oBrandEntity;
import com.eascs.brand.form.O2oBranPage;
import com.eascs.brand.vo.BrandAndPartnerVo;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class O2oBrandService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	public static final int status_delete=2;
	public static final int status_normal=1;
	@Autowired
	O2oBrandDao brandDao;
	
	@Reference
	SequenceService sequenceService;
	
	@Reference
	WorkFlowService workFlowService;

	public List<Object[]> searchBrandPage(String keywords) {
		StringBuffer querySql = new StringBuffer();
		querySql.append("SELECT OBI.ID,OBI.BRAND_NAME,OBI.BRAND_CODE FROM O2O_BRAND_INFO OBI WHERE 1=1 ");
		querySql.append(" AND OBI.wf_status = 0  and OBI.BRAND_NAME like ? ORDER BY OBI.UPDATE_TIME DESC ");
		return brandDao.findObjectsList(querySql.toString(), "%" + keywords + "%");
	}

	public PageResult<Object[]> getBrandPage(O2oBranPage branForm) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, branForm.getPageSize(), branForm.getPageIndex());
		StringBuffer querySql = new StringBuffer();
		querySql.append("SELECT OBI.ID,OBI.BRAND_NAME,OBI.BRAND_CODE,OBI.HOST_PROVINCE_NAME,OBI.THE_INDUSTRY");
		querySql.append(" ,OBI.CREATE_TIME,OBI.WF_STATUS, OBI.OPERATOR_ID FROM O2O_BRAND_INFO OBI WHERE 1=1 ");
		if (!StringUtil.isEmpty(branForm.getBrandName())) {
			querySql.append(" AND OBI.BRAND_NAME LIKE ? ");
			sqlPageQuery.addLikeParam(branForm.getBrandName());
		}
		if (!StringUtil.isEmpty(branForm.getHostProvince())) {
			querySql.append(" AND OBI.HOST_PROVINCE = ? ");
			sqlPageQuery.addParam(branForm.getHostProvince());
		}
		if (!StringUtil.isEmpty(branForm.getCreateTime())) {
			querySql.append(" AND OBI.CREATE_TIME >= ? ");
			sqlPageQuery.addParam(branForm.getCreateTime());
		}
		
		if (!StringUtil.isEmpty(branForm.getCreateEndTime())) {
			querySql.append(" AND OBI.CREATE_TIME < ?");
			sqlPageQuery.addParam(DateUtils.formateStandDate(DateUtils.addDate(DateUtils.formateStandDate(branForm.getCreateEndTime()), 1)));
		}
		if (StringUtils.isNotBlank(branForm.getStatus())) {
			querySql.append(" AND OBI.WF_STATUS= ? ");
			sqlPageQuery.addParam(branForm.getStatus());
		}
		querySql.append(" AND OBI.STATUS = ? ");
		sqlPageQuery.addParam(status_normal);
		querySql.append(" ORDER BY OBI.UPDATE_TIME DESC ");
		sqlPageQuery.setQuerySql(querySql.toString());
		return brandDao.findDataWithPage(sqlPageQuery);
	}
	public PageResult<Object[]> getBrandInfo(O2oBranPage branForm) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class,branForm.getPageSize(), branForm.getPageIndex());
		StringBuffer querySql = new StringBuffer();
		querySql.append(" SELECT create_time,brand_name,host_province_name,");
		querySql.append(" (SELECT item_name FROM pub_dditem_o2o WHERE item_code = b.brand_source AND dd_no = '51006') AS brand_source,");
		querySql.append(" (SELECT item_name FROM pub_dditem_o2o WHERE item_code = b.popularity AND dd_no = '51007') AS popularity,");
		querySql.append(" brand_create_time,");
		querySql.append(" (SELECT item_name FROM pub_dditem_o2o WHERE item_code = b.the_industry AND dd_no = 'l6rkja9fqcb0a') AS the_industry,");
		querySql.append(" (SELECT item_name FROM pub_dditem_o2o WHERE item_code = b.wf_status AND dd_no = '51004') AS wf_status");
		querySql.append(" FROM o2o_brand_info b");
		querySql.append(" WHERE 1=1 ");
		if (!StringUtil.isEmpty(branForm.getBrandName())) {
			querySql.append(" AND b.BRAND_NAME LIKE ? ");
			sqlPageQuery.addLikeParam(branForm.getBrandName());
		}
		if (!StringUtil.isEmpty(branForm.getHostProvince())) {
			querySql.append(" AND b.HOST_PROVINCE = ? ");
			sqlPageQuery.addParam(branForm.getHostProvince());
		}
		if (!StringUtil.isEmpty(branForm.getCreateTime())) {
			querySql.append(" AND b.CREATE_TIME >= ? ");
			sqlPageQuery.addParam(branForm.getCreateTime());
		}
		
		if (!StringUtil.isEmpty(branForm.getCreateEndTime())) {
			querySql.append(" AND b.CREATE_TIME < ?");
			sqlPageQuery.addParam(DateUtils.formateStandDate(DateUtils.addDate(DateUtils.formateStandDate(branForm.getCreateEndTime()), 1)));
		}
		if (StringUtils.isNotBlank(branForm.getStatus())) {
			querySql.append(" AND b.WF_STATUS= ? ");
			sqlPageQuery.addParam(branForm.getStatus());
		}
		querySql.append(" AND b.STATUS = ? ");
		sqlPageQuery.addParam(status_normal);
		sqlPageQuery.setQuerySql(querySql.toString());
		return brandDao.findDataWithPage(sqlPageQuery);
	}
	public O2oBrandEntity getEntityById(String id) {
		return brandDao.getById(O2oBrandEntity.class, id);
	}

//	@Transactional(transactionManager = "o2oTransactionManager")
//	public int insert(O2oBrandEntity brandEntity) {
//		return brandDao.insert(brandEntity);
//	}

//	@Transactional(transactionManager = "o2oTransactionManager")
//	public int update(O2oBrandEntity brandEntity) {
//		return brandDao.updateById(brandEntity);
//	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据品牌名称或品牌code查询是否有重复的名称或code
	 *               </p>
	 * @author CXW
	 * @date 2016年11月16日 下午2:59:47
	 * @version V1.0
	 */
	public int checkNameAndCode(String brandName, String brandCode) {
		String sql = "";
		if (!StringUtil.isEmpty(brandName)) {
			sql = "select count(*) from o2o_brand_info where brand_name = ? ";
			return brandDao.findInteger(sql, brandName);
		}
		if (!StringUtil.isEmpty(brandCode)) {
			sql = "select count(*) from o2o_brand_info where brand_code = ?";
			return brandDao.findInteger(sql, brandCode);
		}
		return -1;
	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据品牌名称或品牌code查询是否有重复的名称或code
	 *               </p>
	 * @author CXW
	 * @date 2016年11月18日 下午1:52:04
	 * @version V1.0
	 */
	public boolean getNameAndCode(String brandName, String brandCode) {
		SqlPageQuery<O2oBrandEntity> sqlPageQuery = new SqlPageQuery<>(O2oBrandEntity.class, 10, 0);
		StringBuffer querySql = new StringBuffer();
		querySql.append("select * from o2o_brand_info where 1=1 ");
		
		if (!StringUtil.isEmpty(brandName)) {
			querySql.append(" and brand_name = ? ");
			sqlPageQuery.addParam(brandName);
		}
		if (!StringUtil.isEmpty(brandCode)) {
			querySql.append(" and brand_code = ? ");
			sqlPageQuery.addParam(brandName);
		}
		querySql.append(" AND status = 1 ");
		sqlPageQuery.setQuerySql(querySql.toString());
		PageResult<O2oBrandEntity> findDataWithPage = brandDao.findDataWithPage(sqlPageQuery);
		int size = findDataWithPage.getData().size(); 
		if (size == 0) {
			return true;
		}
		return false;
	}
	/**
	 * 查询品牌和渠道名称、code
	 * @param loanapplyNo
	 * @return
	 */
	public BrandAndPartnerVo queryCodeAndName(String loanapplyNo){
		return brandDao.queryCodeAndName(loanapplyNo);
	}
	
	
	
	public ModelResult<Boolean> insert(O2oBrandEntity entity){
		ModelResult<Boolean> modelResult=new ModelResult<>();
		if (entity == null ) {
			modelResult.withError("insert.error", "O2oBrandService insert is null");
		}
		String brandCode=sequenceService.getSeq("O2O_BRAND_NO", 5, "BRAND");
		entity.setBrandCode(brandCode);
		boolean model =brandDao.insert(entity);
		modelResult.withModel(model);
		return modelResult;
	}
	
	public ModelResult<Boolean> delete(String brandId){
		ModelResult<Boolean> modelResult=new ModelResult<>();
		if (StringUtils.isBlank(brandId)) {
			modelResult.withError("delete.error", "O2oBrandService delete is null");
		}
		
		boolean model =brandDao.delete(brandId);
		modelResult.withModel(model);
		return modelResult;
	}
	
	public ModelResult<Boolean> update(O2oBrandEntity entity){
		ModelResult<Boolean> modelResult=new ModelResult<>();
		if (entity == null ) {
			modelResult.withError("update.error", "O2oBrandService update is null");
		}

		String brandId =entity.getId();
		if (StringUtils.isBlank(brandId)) {
			modelResult.withError("update.error", "O2oBrandService update is null");
		}
		
		/**对象update操作时，防止为传入null数据替换状态、时间等数据*/
		O2oBrandEntity pe = brandDao.queryBrandEntityById(brandId);
		if (pe == null ) {
			modelResult.withError("update.error", "O2oBrandService update is null");
		}
		entity.setBrandCode(pe.getBrandCode());
		entity.setCreateTime(pe.getCreateTime());
		entity.setWfStatus(pe.getWfStatus());
		entity.setStatus(pe.getStatus());
		
		boolean model =brandDao.update(entity);
		modelResult.withModel(model);
		return modelResult;
	}

	
	public ModelResult<O2oBrandEntity> queryBrandEntityById(String brandId){
		ModelResult<O2oBrandEntity> modelResult=new ModelResult<>();
		if (StringUtils.isBlank(brandId)) {
			modelResult.withError("query.error", "O2oBrandService queryBrandEntityById brandId is null");
		}
		
		O2oBrandEntity model = brandDao.queryBrandEntityById(brandId);
		modelResult.withModel(model);
		return modelResult;
	}
	
	/**
	 * @Title: startUp
	 * @Description: 启动品牌申请
	 * @author 
	 * @param brandId
	 * @return
	 * @return ModelResult<Boolean>
	 * @throws
	 * @date 2017年3月16日 上午10:02:08
	 */
	public ModelResult<Boolean> startUp(String brandId) {
		try {
			O2oBrandEntity brand = brandDao.queryBrandEntityById(brandId);
			WFRequestParam param = new WFRequestParam();
			param.setReferId(brandId);
			param.setReferCode(brand.getBrandCode());
			param.setReferUrl("/rbrand/view_flow");
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_AUDIT_BP));
			param.setProcessVersion("v1");
			User user = UserHolder.getUser();
			param.setAppliedby(user.getNo());
			param.setAppliedbyName(user.getCname());
			param.setOrgNo(brand.getOrgId());
			param.setAppliedDes("品牌名称：" + brand.getBrandName() + ", 经办人：" + user.getCname());
			logger.info("启动品牌申请，参数有品牌id：【{}】，品牌编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", brandDao, brand.getBrandCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), brand.getOrgId());
			ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess() && modelResult.getModel()) {
				brandDao.processBrandStart(brandId);
			} else {
				logger.error("启动品牌申请失败，品牌id：【{}】，错误信息{}", brandDao, modelResult.getErrMsg());
			}
			return modelResult;
		} catch (Exception e) {
			logger.error("启动品牌申请失败，品牌id：【{}】，错误：{}，", brandDao, e.getMessage());
			return new ModelResult<Boolean>("brand error", "启动品牌申请失败");
		}
	}
}
